import { Inject, Injectable } from '@nestjs/common';
// import { CreateAdminDto } from './dto/create-admin.dto';
// import { UpdateAdminDto } from './dto/update-admin.dto';
import { AdminEntity } from './entities/admin.entity';
import { Repository } from 'typeorm';
import * as CryptoJS from 'crypto-js';
import { ADMIN_ROOT } from 'src/config';
import { JwtService } from '@nestjs/jwt';
import { LoginAdminDto } from './dto/login-admin.dto';
import { BusinessException } from 'src/common/exceptions/business.exception';
import { BUSINESS_ERROR_CODE } from 'src/common/exceptions/business.error.codes';
import {} from 'src/utils';

@Injectable()
export class AdminService {
  constructor(
    @Inject('ADMIN_USER_REPOSITORY') //注入用户数据库依赖
    private readonly adminRepository: Repository<AdminEntity>,
    private jwtService: JwtService,
  ) {}
  async createSuperUser() {
    const superUser = this.adminRepository.create(ADMIN_ROOT);
    await this.adminRepository.save(superUser);
  }

  async initSuperUser() {
    const is = await this.adminRepository.findOne({
      where: ADMIN_ROOT,
    });

    // 判断是否有超级管理员
    if (!is) {
      this.createSuperUser(); //创建创建管理员
    }
  }

  async login(user: LoginAdminDto) {
    const findUser = await this.adminRepository.findOne({
      select: [
        'account',
        'avatar_url',
        'role',
        'email',
        'name',
        'phoneNumber',
        'id',
      ],
      where: {
        account: user.username,
        password: CryptoJS.MD5(user.password).toString(),
      },
    });
    if (!findUser) {
      throw new BusinessException({
        code: BUSINESS_ERROR_CODE.COMMON,
        message: '账号密码错误',
      });
    }
    const userData: AdminEntity = {
      ...findUser,
      avatar_url: findUser.avatar_url,
    };
    return {
      user: {
        ...userData,
        roles: [userData.role],
      },
      token: this.createToken(findUser).access_token,
    };
  }

  // create(createAdminDto: CreateAdminDto) {
  //   return 'This action adds a new admin';
  // }

  // findAll() {
  //   return `This action returns all admin`;
  // }

  findOne(id: number) {
    return this.adminRepository.findOne({
      where: { id },
    });
  }
  createToken(payload: AdminEntity) {
    const user: Partial<AdminEntity> = {
      account: payload.account,
      id: payload.id,
      role: payload.role,
    };
    const access_token = this.jwtService.sign(user);
    return {
      access_token,
      type: 'Bearer',
    };
  }
  // update(id: number, updateAdminDto: UpdateAdminDto) {
  //   return `This action updates a #${id} admin`;
  // }

  // remove(id: number) {
  //   return `This action removes a #${id} admin`;
  // }
}
